package com.liao.tensquare.utils;

import com.google.gson.internal.$Gson$Preconditions;
import com.liao.tensquare.constants.TokenConstants;
import com.liao.tensquare.entity.JWTInfo;
import com.liao.tensquare.exception.UserTokenException;
import io.jsonwebtoken.*;

import java.util.Date;

public class JwtTokenUtil {

    public static String generateToken(JWTInfo jwtInfo, String secretKey) {
        long l = System.currentTimeMillis() + 1000 * 60 * 60 * 4;
        return Jwts.builder()
                .setSubject(jwtInfo.getAccount())
                .claim(TokenConstants.JWT_KEY_ID, jwtInfo.getId())
                .claim(TokenConstants.JWT_KEY_NICKNAME, jwtInfo.getNickname())
                .claim(TokenConstants.JWT_KEY_USER_ACCOUNT, jwtInfo.getAccount())
                .setIssuedAt(new Date())//签发时间
                .setExpiration(new Date(l))//过期时间
                .signWith(SignatureAlgorithm.HS256, secretKey)
                .compact();
    }

    public static Claims getInfoFromToken(String authToken, String secretKey) throws Exception {
//        try {
            return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(authToken).getBody();
//        } catch (ExpiredJwtException e) {
//            throw new UserTokenException("Token过期!");
//        } catch (SignatureException e){
//            throw new UserTokenException("Token错误!");
//        }
    }

}
